/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.modular.workstep.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import vip.xiaonuo.core.consts.CommonConstant;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.modular.pro.service.ProService;
import vip.xiaonuo.modular.task.entity.Task;
import vip.xiaonuo.modular.task.service.TaskService;
import vip.xiaonuo.modular.workstep.entity.WorkStep;
import vip.xiaonuo.modular.workstep.enums.WorkStepExceptionEnum;
import vip.xiaonuo.modular.workstep.mapper.WorkStepMapper;
import vip.xiaonuo.modular.workstep.param.WorkStepParam;
import vip.xiaonuo.modular.workstep.result.WorkStepResult;
import vip.xiaonuo.modular.workstep.service.WorkStepService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.modular.worksteproute.entity.WorkStepRoute;
import vip.xiaonuo.modular.worksteproute.service.WorkStepRouteService;
import vip.xiaonuo.sys.modular.org.entity.SysOrg;
import vip.xiaonuo.sys.modular.org.enums.SysOrgExceptionEnum;
import vip.xiaonuo.sys.modular.org.param.SysOrgParam;
import vip.xiaonuo.util.AutoCode;

import javax.annotation.Resource;
import java.io.Console;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 工序service接口实现类
 *
 * @author yxc
 * @date 2022-05-24 10:24:22
 */
@Service
public class WorkStepServiceImpl extends ServiceImpl<WorkStepMapper, WorkStep> implements WorkStepService {
    @Resource
    private WorkStepRouteService workStepRouteService;
    @Resource
    private TaskService taskService;
    @Resource
    private ProService proService;

    @Override
    public PageResult<WorkStepResult> page(WorkStepParam workStepParam) {

        return new PageResult<>(this.baseMapper.page(PageFactory.defaultPage(),getQueryWrapper(workStepParam)));

    }
    private QueryWrapper getQueryWrapper(WorkStepParam workStepParam){
        QueryWrapper<WorkStep> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(workStepParam)) {

            // 根据工序编号 查询
            if (ObjectUtil.isNotEmpty(workStepParam.getCode())) {
                queryWrapper.lambda().like(WorkStep::getCode, workStepParam.getCode());
            }
            // 根据备注 查询
            if (ObjectUtil.isNotEmpty(workStepParam.getRemarks())) {

                queryWrapper.lambda().like(WorkStep::getRemarks, workStepParam.getRemarks());
            }
            // 根据工序名称 查询
            if (ObjectUtil.isNotEmpty(workStepParam.getName())) {
                queryWrapper.lambda().like(WorkStep::getName, workStepParam.getName());
            }
            // 根据不良品项 查询使用instr进行模糊查询
            if (ObjectUtil.isNotEmpty(workStepParam.getMulBadItem())) {
                String[] mulBadItemlist=workStepParam.getMulBadItem().split(";");
                queryWrapper.nested(item->{
                            for ( String mulBadItem: mulBadItemlist)
                            {
                                item.lambda().apply("instr(concat(';',mul_bad_item,';'),concat(';',{0},';'))",mulBadItem).or();
                            }
                        }
                );
            }
            //根据动态字段 查询
            if (ObjectUtil.isNotEmpty(workStepParam.getJosn())) {
                //调用动态字段查询方法
                proService.dynamicFieldQuery("dw_work_step", queryWrapper, workStepParam.getJosn());
            }
        }
        queryWrapper.orderByDesc("n.create_time");
        return queryWrapper;
    }

    @Override
    public List<WorkStepResult> list(WorkStepParam workStepParam) {
        return this.baseMapper.page(getQueryWrapper(workStepParam));
    }

    @Override
    public void add(WorkStepParam workStepParam) {
        //默认编码
        if(ObjectUtil.isEmpty(workStepParam.getCode()))
        {

            //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            workStepParam.setCode(AutoCode.getCodeByService("dw_work_step", this.getClass(), 0));

        }
        //将json转换为json字符串
        String jsonToString = JSONArray.toJSON(workStepParam.getJosn()).toString();
        workStepParam.setJosn(jsonToString);
        //校验编码和名称
        checkParam(workStepParam,false);
        WorkStep workStep = new WorkStep();
        BeanUtil.copyProperties(workStepParam, workStep);
        this.save(workStep);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<WorkStepParam> workStepParamList) {
        workStepParamList.forEach(workStepParam -> {
            checkdelete(workStepParam);

            this.removeById(workStepParam.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(WorkStepParam workStepParam) {
        checkParam(workStepParam,true);
        WorkStep workStep = this.queryWorkStep(workStepParam);
        BeanUtil.copyProperties(workStepParam, workStep);
        //避免空{}不能存入Josn
        if (ObjectUtil.isEmpty(workStepParam.getJosn())) {
            workStep.setJosn(JSONArray.toJSON("{}"));
        }
        //将js值转换为Josn
        if (ObjectUtil.isNotEmpty(workStepParam.getJosn())) {
            String josnToString = JSONArray.toJSON(workStepParam.getJosn()).toString();
            workStep.setJosn(josnToString);
        }
        this.updateById(workStep);
    }

    @Override
    public WorkStep detail(WorkStepParam workStepParam) {
        return this.queryWorkStep(workStepParam);
    }

    /**
     * 获取工序
     *
     * @author yxc
     * @date 2022-05-24 10:24:22
     */
    private WorkStep queryWorkStep(WorkStepParam workStepParam) {
        WorkStep workStep = this.getById(workStepParam.getId());
        if (ObjectUtil.isNull(workStep)) {
            throw new ServiceException(WorkStepExceptionEnum.NOT_EXIST);
        }
        return workStep;
    }

    @Override
    public void export(WorkStepParam workStepParam) {
        List<WorkStep> list = this.list(getQueryWrapper(workStepParam));
        PoiUtil.exportExcelWithStream("SnowyWorkStep.xls", WorkStep.class, list);
    }
    /**
     * 校验参数，检查是否存在相同的名称和编码
     *
     * @author xuyuxiang
     * @date 2020/3/25 21:23
     */
    private void checkParam(WorkStepParam workStepParam ,boolean isExcludeSelf ) {
        String name = workStepParam.getName();
        String code = workStepParam.getCode();
        Long id = workStepParam.getId();

        LambdaQueryWrapper<WorkStep> queryWrapperByName = new LambdaQueryWrapper<>();
        queryWrapperByName.eq(WorkStep::getName, name);
        LambdaQueryWrapper<WorkStep> queryWrapperByCode = new LambdaQueryWrapper<>();
        queryWrapperByCode.eq(WorkStep::getCode, code);
        if (isExcludeSelf) {
            queryWrapperByName.ne(WorkStep::getId, id);
            queryWrapperByCode.ne(WorkStep::getId, id);
        }
        int countByName = this.count(queryWrapperByName);
        int countByCode = this.count(queryWrapperByCode);
        if (countByName >= 1) {
            throw new ServiceException(WorkStepExceptionEnum.ORG_NAME_REPEAT);
        }
        if (countByCode >= 1) {
            throw new ServiceException(WorkStepExceptionEnum.ORG_CODE_REPEAT);
        }

    }
    /**
     * 工序删除校验
     */
    private void checkdelete(WorkStepParam workStepParam )
    {
        //工艺路线校验
        LambdaQueryWrapper<WorkStepRoute> queryWrapperByRoute = new LambdaQueryWrapper<>();
        //并行方式
        //queryWrapperByRoute.eq(WorkStepRoute::getSource, workStepParam.getId()).or().eq(WorkStepRoute::getTarget, workStepParam.getId());
        //非并行
        queryWrapperByRoute.eq(WorkStepRoute::getWorkStepId, workStepParam.getId());
        //任务校验
        LambdaQueryWrapper<Task> queryWrapperByTask = new LambdaQueryWrapper<>();
        queryWrapperByTask.eq(Task::getWorkStepId,workStepParam.getId());
        int countByTask = taskService.count(queryWrapperByTask);
        int countByRoute = workStepRouteService.count(queryWrapperByRoute);
        if (countByRoute > 0) {
            throw new ServiceException(5, workStepParam.getName()+"工序在工艺中使用不允许删除");
        }
        if (countByTask > 0) {
            throw new ServiceException(5, workStepParam.getName()+"工序在任务中使用不允许删除");
        }
    }

}
